<template>
  <div class="dashboard-container">

    <!-- 数据统计 -->
    <el-row :gutter="10" class="mt-5">
      <!-- 合同设计 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">合同设计</span>
              <el-tag type="danger" size="small">任务</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 flex-1">
            <div class="flex-y-center">
              <span class="text-lg transition-all duration-300 hover:scale-110">
                {{ contractDesignPager?.total }}
              </span>
            </div>
          </div>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>更新时间</span>
            <span>{{ formattedTime }}</span>
          </div>
        </el-card>
      </el-col>
      

      <!-- 合同施工 -->
      <el-col :span="6" :xs="24" class="mb-xs-3">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">合同施工任务</span>
              <el-tag type="danger" size="small">任务</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 flex-1">
            <div class="flex-y-center">
              <span class="text-lg transition-all duration-300 hover:scale-110">
                {{ contractTaskPager?.total }}
              </span>
            </div>
          </div>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>更新时间</span>
            <span>{{ formattedTime }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 浏览量(PV) -->
      <el-col :span="6" :xs="24">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">申购</span>
              <el-tag type="danger" size="small">任务</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 flex-1">
            <div class="flex-y-center">
              <span class="text-lg transition-all duration-300 hover:scale-110">
                {{ purchasePager?.total }}
              </span>
            </div>
          </div>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>更新时间</span>
            <span>{{ formattedTime }}</span>
          </div>
        </el-card>
      </el-col>

       <!-- 浏览量(PV) -->
      <el-col :span="6" :xs="24">
        <el-card shadow="never" class="h-full flex flex-col">
          <template #header>
            <div class="flex-x-between">
              <span class="text-gray">采购</span>
              <el-tag type="danger" size="small">任务</el-tag>
            </div>
          </template>

          <div class="flex-x-between mt-2 flex-1">
            <div class="flex-y-center">
              <span class="text-lg transition-all duration-300 hover:scale-110">
                {{ reimbursePager?.total }}
              </span>
            </div>
          </div>

          <div class="flex-x-between mt-2 text-sm text-gray">
            <span>更新时间</span>
            <span>{{ formattedTime }}</span>
          </div>
        </el-card>
      </el-col>

    </el-row>


    <!-- <el-card shadow="never" class="mt-2">
      <div class="flex flex-wrap">
        <div class="flex-1 flex items-start">
          <img class="w80px h80px rounded-full" :src="userStore.userInfo.avatar" />
          <div class="ml-5">
          
            <p class="text-sm text-gray">今日天气晴朗，气温在15℃至25℃之间，东南风。</p>
          </div>
        </div>
      </div>
    </el-card> -->

    <el-row :gutter="10" class="mt-5">
      <!-- 访问趋势统计图 -->
      <el-col :xs="24" :span="24">
        <el-card>
          <p>合同设计：</p>
          <el-table :data="contractDesignPager?.list" highlight-current-row border class="data-table__content">
            <el-table-column label="合同名称" prop="name" min-width="200" />
            <el-table-column label="状态" prop="status" width="150">
              <template #default="scope">
                <el-tag v-if="scope.row.status" type="success">
                  {{ Contract_Status_Label[scope.row.status] }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding-bottom: 20px"></div>
          <p>合同施工任务：</p>
          <el-table :data="contractTaskPager?.list" highlight-current-row border class="data-table__content">
            <el-table-column label="合同名称" prop="contractName" min-width="200" />
             <el-table-column label="施工节点" prop="nodeName" min-width="200" />
            <el-table-column label="任务名称" prop="taskName" min-width="200" />
            <el-table-column label="任务状态" prop="status" min-width="200" />
          </el-table>
          <div style="padding-bottom: 20px"></div>
          <p>申购任务：</p>
          <el-table :data="purchasePager?.list" highlight-current-row border class="data-table__content">
            <el-table-column label="申购标题" prop="title" min-width="200" />
            <el-table-column label="金额" prop="amount" width="150" />
            <el-table-column label="申请人" prop="username" width="150" />
            <el-table-column label="状态" prop="status" width="150" >
              <template #default="scope">
                   {{ Purchase_Status_Label[scope.row.status] }}
              </template>
            </el-table-column>
          </el-table>
           <p>报销任务：</p>
          <el-table :data="reimbursePager?.list" highlight-current-row border class="data-table__content">
            <el-table-column label="申购标题" prop="title" min-width="200" />
            <el-table-column label="金额" prop="amount" width="150" />
            <el-table-column label="申请人" prop="username" width="150" />
            <el-table-column label="状态" prop="status" width="150" >
              <template #default="scope">
                   {{ Reimburse_Status_Label[scope.row.status] }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
     
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

import { dayjs } from "element-plus";
import LogAPI, { VisitStatsVO, VisitTrendVO } from "@/api/system/log.api";
import { useUserStore } from "@/store/modules/user.store";
import { useTransition, useDateFormat } from "@vueuse/core";
import { useOnlineCount } from "@/composables/useOnlineCount";
import DashboardAPI, { FeePageVO, ContractTaskVO } from "@/api/business/dashboard/dashboard.api";
import { ContractDesignPageVO } from "@/api/flow/contractDesign.api";
import { Contract_Status_Label } from "@/api/flow/contract.api";
import { Purchase_Status_Label,PurchasePageVO } from "@/api/fee/purchase.api";
import { Reimburse_Status_Label,ReimbursePageVO } from "@/api/fee/reimburse.api";

const contractDesignPager = ref<PageResult<ContractDesignPageVO[]>>();
const contractTaskPager = ref<PageResult<ContractTaskVO[]>>();
const purchasePager = ref<PageResult<PurchasePageVO[]>>();
const reimbursePager = ref<PageResult<ReimbursePageVO[]>>();

// 在线用户数量组件相关
const { onlineUserCount, lastUpdateTime, isConnected } = useOnlineCount();

// 记录上一次的用户数量用于计算趋势
const previousCount = ref(0);

// 监听用户数量变化，计算趋势
watch(onlineUserCount, (newCount, oldCount) => {
  if (oldCount > 0) {
    previousCount.value = oldCount;
  }
});

// 格式化时间戳
const formattedTime = computed(() => {
  return useDateFormat(new Date(), "HH:mm:ss").value;
});

interface VersionItem {
  id: string;
  title: string; // 版本标题（如：v2.4.0）
  date: string; // 发布时间
  content: string; // 版本描述
  link: string; // 详情链接
  tag?: string; // 版本标签（可选）
}

const userStore = useUserStore();


// 当前时间（用于计算问候语）
const currentDate = new Date();





// 访问趋势日期范围（单位：天）
const visitTrendDateRange = ref(7);
// 访问趋势图表配置
const visitTrendChartOptions = ref();

/**
 * 获取访客统计数据
 */
const loadTaskList = () => {
  DashboardAPI.loadContractDesign().then((data) => {
    contractDesignPager.value = data;
  });
  DashboardAPI.loadContractTask().then((data) => {
    contractTaskPager.value = data;
  });
  DashboardAPI.loadPurchase().then((data) => {
    purchasePager.value = data;
  });
  DashboardAPI.loadReimburse().then((data) => {
    reimbursePager.value = data;
  });
  DashboardAPI.loadMyContracts().then((data) => { 
  });
};

/**
 * 获取访问趋势数据，并更新图表配置
 */
const fetchVisitTrendData = () => {
  const startDate = dayjs()
    .subtract(visitTrendDateRange.value - 1, "day")
    .toDate();
  const endDate = new Date();

};

/**
 * 更新访问趋势图表的配置项
 *
 * @param data - 访问趋势数据
 */
const updateVisitTrendChartOptions = (data: VisitTrendVO) => {
  console.log("Updating visit trend chart options");

  visitTrendChartOptions.value = {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["浏览量(PV)", "访客数(UV)"],
      bottom: 0,
    },
    grid: {
      left: "1%",
      right: "5%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: data.dates,
    },
    yAxis: {
      type: "value",
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "浏览量(PV)",
        type: "line",
        data: data.pvList,
        areaStyle: {
          color: "rgba(64, 158, 255, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#4080FF",
        },
        lineStyle: {
          color: "#4080FF",
        },
      },
      {
        name: "访客数(UV)",
        type: "line",
        data: data.ipList,
        areaStyle: {
          color: "rgba(103, 194, 58, 0.1)",
        },
        smooth: true,
        itemStyle: {
          color: "#67C23A",
        },
        lineStyle: {
          color: "#67C23A",
        },
      },
    ],
  };
};

/**
 * 根据增长率计算对应的 CSS 类名
 *
 * @param growthRate - 增长率数值
 */
const computeGrowthRateClass = (growthRate?: number): string => {
  if (!growthRate) {
    return "text-[--el-color-info]";
  }
  if (growthRate > 0) {
    return "text-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "text-[--el-color-success]";
  } else {
    return "text-[--el-color-info]";
  }
};

// 监听访问趋势日期范围的变化，重新获取趋势数据
watch(
  () => visitTrendDateRange.value,
  (newVal) => {
    console.log("Visit trend date range changed:", newVal);
    fetchVisitTrendData();
  },
  { immediate: true }
);

// 组件挂载后加载访客统计数据和通知公告数据
onMounted(() => {
  loadTaskList();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }

    &:hover {
      transform: translateX(5px);
    }

    .version-content {
      margin-bottom: 12px;
      font-size: 13px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
